from django.shortcuts import render

# Create your views here.
from rest_framework.response import Response
from rest_framework.views import APIView
import datetime
from django_redis import get_redis_connection
from bms_core.create_token import CreateToken
from bms_core.models import People


class Login(APIView):
    def post(self, request):
        # 保证username是唯一的
        username = request.data.get('username')
        password = request.data.get('password')
        user = People.objects.filter(user=username).first()
        if not user:
            return Response('Failed')
        if user.password != password:
            return Response('Failed')
        r = get_redis_connection('default')
        user.logintime = datetime.datetime.now()
        login_time = user.logintime.isoformat()
        token = CreateToken(username,password).create_token(user.id)
        r.hset('token',username,token)
        # TODO:默认是60s，后面做一个可配置的
        timeout = 60
        data = {
            "login_time":login_time,
            "timeout":timeout,
            "token":token
        }
        return Response({"data":data})